package com.woniu.service.impl;



import com.woniu.common.enums.ExceptionCode;
import com.woniu.common.exception.CustomException;
import com.woniu.common.utils.sign.Md5Utils;
import com.woniu.dto.RegisterDto;
import com.woniu.entity.User;
import com.woniu.mapper.UserMapper;
import com.woniu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public User findByUserAccountAndPassword(String userAccount, String password) {
        System.out.println("password = " + password);
        User user = new User();
        user.setUserAccount(userAccount);
        //把用户输入的密码做两次Md5
        user.setUserPassword(Md5Utils.hash(Md5Utils.hash(password)));
        return userMapper.selectOne(user);
    }

    @Override
    public void register(RegisterDto registerDto) {

        //检查验证码是否正确
        String codeInRedis = stringRedisTemplate.opsForValue().get("user_register_cellphoneCode_" + registerDto.getCellPhone());
        if (codeInRedis == null || !codeInRedis.equals(registerDto.getVerifyCode())){
            throw new CustomException(ExceptionCode.INVALID_KAPTCHA);
        }
        //验证手机号码是否可用
        User user = new User();
        user.setUserPhone(registerDto.getCellPhone());
        User result = userMapper.selectOne(user);
        if (result != null){
            throw new CustomException(ExceptionCode.USER_ACCOUNT_IN_USE);
        }
        //Md5两次密码
        user.setUserPassword(Md5Utils.hash(Md5Utils.hash(registerDto.getUserPassword())));
        user.setUserAccount(registerDto.getCellPhone());
        user.setUserStatus(1);
        user.setUserType(2);

        userMapper.insert(user);

    }
}
